/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * newUser.java
 *
 * Created on 2009-12-2, 22:08:32
 */
package cititool.chat.client.UI;

import cititool.chat.client.ClientContext;
import cititool.chat.client.handler.ClientOperation;
import cititool.chat.client.handler.ClientRecHandler;
import cititool.model.UserInfo;
import cititool.util.ComponentHelper;
import cititool.util.StringHelper;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author Administrator
 */
public class UserInfoFrame extends javax.swing.JFrame {

    /** Creates new form newUser */
    public UserInfoFrame(String username, final Socket s) {        
        this.setTitle( username);
        this.curuser = username;
        initComponents();        
        ClientContext.instance();
        ClientContext.setCurSocket(s);
        initdata();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        listpane = new javax.swing.JTabbedPane();
        userlistarea = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        userTree = new javax.swing.JTree();
        serverlist = new javax.swing.JPanel();
        storefolder = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        clientlog = new javax.swing.JTextPane();
        chattab = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jSplitPane1.setDividerLocation(300);
        jSplitPane1.setLastDividerLocation(300);
        jSplitPane1.setName("jSplitPane1"); // NOI18N
        jSplitPane1.setOneTouchExpandable(true);
        jSplitPane1.setPreferredSize(new java.awt.Dimension(1000, 550));

        listpane.setName("listpane"); // NOI18N
        listpane.setPreferredSize(new java.awt.Dimension(300, 550));

        userlistarea.setName("userlistarea"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        userTree.setName("userTree"); // NOI18N
        userTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                userTreeMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(userTree);

        javax.swing.GroupLayout userlistareaLayout = new javax.swing.GroupLayout(userlistarea);
        userlistarea.setLayout(userlistareaLayout);
        userlistareaLayout.setHorizontalGroup(
            userlistareaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
        );
        userlistareaLayout.setVerticalGroup(
            userlistareaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 536, Short.MAX_VALUE)
        );

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(cititool.MainApp.class).getContext().getResourceMap(UserInfoFrame.class);
        listpane.addTab(resourceMap.getString("userlistarea.TabConstraints.tabTitle"), userlistarea); // NOI18N

        serverlist.setName("serverlist"); // NOI18N

        storefolder.setText(resourceMap.getString("storefolder.text")); // NOI18N
        storefolder.setName("storefolder"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout serverlistLayout = new javax.swing.GroupLayout(serverlist);
        serverlist.setLayout(serverlistLayout);
        serverlistLayout.setHorizontalGroup(
            serverlistLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, serverlistLayout.createSequentialGroup()
                .addContainerGap(59, Short.MAX_VALUE)
                .addComponent(storefolder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );
        serverlistLayout.setVerticalGroup(
            serverlistLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(serverlistLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(serverlistLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(storefolder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(502, Short.MAX_VALUE))
        );

        listpane.addTab(resourceMap.getString("serverlist.TabConstraints.tabTitle"), serverlist); // NOI18N

        jPanel2.setName("jPanel2"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        clientlog.setEditable(false);
        clientlog.setName("clientlog"); // NOI18N
        clientlog.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                clientlogMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(clientlog);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 536, Short.MAX_VALUE)
        );

        listpane.addTab(resourceMap.getString("jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N

        jSplitPane1.setLeftComponent(listpane);

        chattab.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
        chattab.setName("chattab"); // NOI18N
        chattab.setPreferredSize(new java.awt.Dimension(695, 550));

        jPanel3.setName("jPanel3"); // NOI18N
        jPanel3.setPreferredSize(new java.awt.Dimension(695, 519));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 700, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 536, Short.MAX_VALUE)
        );

        chattab.addTab(resourceMap.getString("jPanel3.TabConstraints.tabTitle"), jPanel3); // NOI18N

        jSplitPane1.setRightComponent(chattab);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1011, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void userTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_userTreeMouseClicked
        try {
            // TODO add your handling code here:
            //get userinfo from server
            if (evt.getButton() == MouseEvent.BUTTON3) {
                if (menu == null) {
                    menu = new JPopupMenu();
                    JMenuItem item = new JMenuItem("fresh");
                    item.addActionListener(new ActionListener() {

                        public void actionPerformed(ActionEvent e) {
                            SwingUtilities.invokeLater(new Runnable() {

                                public void run() {
                                    freshtree();
                                }
                            });
                            menu.setVisible(false);
                        }
                    });
                    menu.add(item);
                }
                menu.setLocation(evt.getLocationOnScreen());
                menu.setVisible(true);
            }
            if (evt.getButton() != MouseEvent.BUTTON3) {
                if (menu != null) {
                    menu.setVisible(false);
                }
            }
            //get user information
            TreePath path = getUserTree().getSelectionPath();
            if (path == null) {
                return;
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            if (path != null && node.isLeaf()) {
                if (evt.getButton() == MouseEvent.BUTTON1) {
                    if (evt.getClickCount() == 2) {
                        String username = node.getUserObject().toString();
                        getOper().loadTotalUser(username);
                        UserInfo user = ClientContext.getCacheInfo(username);
                        if (user != null) {
                            getTab().addPanel(user);
                            //get userinfo socket
                        }
                    } else if (evt.getClickCount() == 1) {
                    }
                }
            }
        } catch (IOException ex) {
            ClientContext.productLog("userTreeClick==>", ex);
        } catch (ClassNotFoundException ex) {
            ClientContext.productLog("userTreeClient==>", ex);
        }
}//GEN-LAST:event_userTreeMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        ComponentHelper.filePopup(storefolder, "storedfolder", pref, this);
}//GEN-LAST:event_jButton1ActionPerformed

    private void clientlogMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clientlogMouseClicked
        // TODO add your handling code here:
        ComponentHelper.clearPopup(evt, clientlog);
    }//GEN-LAST:event_clientlogMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTabbedPane chattab;
    private javax.swing.JTextPane clientlog;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTabbedPane listpane;
    private javax.swing.JPanel serverlist;
    private javax.swing.JTextField storefolder;
    private javax.swing.JTree userTree;
    private javax.swing.JPanel userlistarea;
    // End of variables declaration//GEN-END:variables
    private ChatUserinfoTabDef tab;
    private Preferences pref;
    private String curuser;
    private JPopupMenu menu;
    private ClientRecHandler hander;
    private ClientOperation oper;

    private void freshtree() {
        try {
            DefaultTreeModel inittree = new DefaultTreeModel(new DefaultMutableTreeNode("loading user tree..."));
            getUserTree().setModel(inittree);
            getOper().loadUserListFromServer(curuser);


        } catch (IOException ex) {
            ClientContext.warnLog("fresh tree() ", ex);
        } catch (ClassNotFoundException ex) {
            ClientContext.warnLog("fresh tree() ", ex);
        }
    }

    private void loadSetting() {

        pref = Preferences.userRoot().node("/com/chat/usersetting/" + curuser);
        if (!StringHelper.isEmpty(pref.get("storedfolder", ""))) {
            storefolder.setText(pref.get("storedfolder", ""));
        }
        ClientContext.setUserPath(storefolder.getText());
    }

    private void initdata() {

        tab = new ChatUserinfoTabDef(chattab);
        ClientContext.setlog(clientlog);
        //loadSetting
        loadSetting();
        ClientContext.productLog("load user setting over", null);

        //start recv thread
        hander = new ClientRecHandler(ClientContext.getCurrentSocket(), this);
        ClientContext.productLog("start receive thread...", null);

        hander.start();
        try {
            Thread.sleep(200);
        } catch (InterruptedException ex) {
            Logger.getLogger(UserInfoFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        oper = new ClientOperation(ClientContext.getCurrentSocket(), this);
        getOper().setHandler(hander);
        hander.setOperation(getOper());
        try {
            //load self info
            getOper().loadTotalUser(curuser);
            UserInfo current = ClientContext.getCacheInfo(curuser);
            ClientContext.setCurUserInfo(current);
            ClientContext.productLog("load self information over...", null);

        } catch (IOException ex) {
            ClientContext.warnLog("load self info() ", ex);
        } catch (ClassNotFoundException ex) {
            ClientContext.warnLog("load self info() ", ex);
        }
        //load online info
        
        freshtree();        
        ClientContext.productLog("load online over", null);
    }

    /**
     * @return the tab
     */
    public ChatUserinfoTabDef getTab() {
        return tab;
    }

    /**
     * @return the userTree
     */
    public javax.swing.JTree getUserTree() {
        return userTree;
    }

    /**
     * @param userTree the userTree to set
     */
    public void setUserTree(javax.swing.JTree userTree) {
        this.userTree = userTree;
    }

    /**
     * @return the oper
     */
    public ClientOperation getOper() {
        return oper;
    }


    public JPanel getWorkArea(){

        return tab.getWorkArea();
    }
}
